package com.jack.basetech;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jack.Student;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhang_j on 2020/10/29
 */
public class JacksonTest {

    public static void main(String[] args) throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
        Student student = new Student();
        student.setAge(1);
        student.setName("test");
        student.setSex("male");
        List<Student> students = new ArrayList<>();
        students.add(student);
        String s = objectMapper.writeValueAsString(students);
        System.out.println(s);

        JavaType javaType = objectMapper.getTypeFactory().constructCollectionType(List.class, Student.class);
        List<Student> o = objectMapper.readValue(s, javaType);
        o.forEach(a -> System.out.println(a.getSex()+a.getName()+a.getAge()));

        Map<Integer, Student> map = new HashMap<>();
        map.put(1, student);
        s = objectMapper.writeValueAsString(map);
        javaType = objectMapper.getTypeFactory().constructMapType(Map.class, Integer.class, Student.class);
        Map<Integer, Student> result = objectMapper.readValue(s, javaType);
        result.forEach((k,v) -> {
            System.out.println(k + ":" + v.getName());
        });
    }
}
